package org.springcloud.plugin.common.nacos.configuration;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import org.apache.commons.lang3.StringUtils;
import org.springcloud.plugin.common.nacos.constant.NacosConstant;
import org.springcloud.plugin.common.nacos.operation.NacosOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * author: yanggld
 * date: 2019/12/14 12:54
 * version: 1.0
 * description: NacosAutoConfiguration
 */
@Configuration
public class NacosAutoConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public NacosOperation nacosOperation() {
        return new NacosOperation();
    }

    @Bean
    @ConditionalOnMissingBean
    public ConfigService nacosConfigService() throws NacosException {
        Properties properties = createNacosProperties(environment);
        return NacosFactory.createConfigService(properties);
    }
    @Bean
    @ConditionalOnMissingBean
    public NamingService nacosNamingService() throws NacosException {
        Properties properties = createNacosProperties(environment);
        return NamingFactory.createNamingService(properties);
    }

    public static Properties createNacosProperties(Environment environment) {
        Properties properties = new Properties();
        String serverAddr = environment.getProperty(NacosConstant.NACOS_CONFIG_SERVER_ADDR);
        if (StringUtils.isNotEmpty(serverAddr)) {
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        } else {
            throw new IllegalArgumentException("nacos config serverAddr ["+NacosConstant.NACOS_CONFIG_SERVER_ADDR+"] can't be null or empty");
        }
        String namespace = environment.getProperty(NacosConstant.NACOS_CONFIG_NAMESPACE);
        if (StringUtils.isNotEmpty(namespace)) {
            properties.put(PropertyKeyConst.NAMESPACE, namespace);
        }
        String clusterName = environment.getProperty(NacosConstant.NACOS_CONFIG_CLUSTER_NAME);
        if (StringUtils.isNotEmpty(clusterName)) {
            properties.put(PropertyKeyConst.CLUSTER_NAME, clusterName);
        }
        return properties;
    }
}
